﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using netcoreweb.Areas.Admin.ViewModels;
using netcoreweb.Areas.Admin.DataContext;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Logging;

namespace netcoreweb.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class LoginController : Controller
    {
        //构造函数注入上下文
        private readonly netcorewebContext _context;
        private readonly ILogger _logger;

        public LoginController(netcorewebContext Context, ILogger<LoginController> logger)
        {
            _context = Context;
            _logger = logger;
        }

        [HttpGet]
        public IActionResult Index()
        {
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

        [HttpPost]
        public IActionResult Index(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                bool hr = _context.HasUser(model.UserName,model.Password);
                if (hr)
                {
                    //记录cookie
                    var userClaims = new List<Claim>()
                    {
                        new Claim(ClaimTypes.Name, model.UserName),
                        new Claim(ClaimTypes.Email, "sunguanhu@126.com")
                    };
    
                    var grandmaIdentity =
                        new ClaimsIdentity(userClaims, CookieAuthenticationDefaults.AuthenticationScheme);
                    var userPrincipal = new ClaimsPrincipal(new[] { grandmaIdentity });
                    HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal);

                    //记录Session
                    //HttpContext.Session.Set("CurrentUser", System.Text.Encoding.Default.GetBytes(model.UserName));
                     //验证是否授权成功
                    if (userPrincipal.Identity.IsAuthenticated)
                    {
                        _logger.LogInformation("用户验证成功");
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ViewBag.ErrorInfo = "未开启cookie功能，无法登录！";
                        _logger.LogWarning("未开启cookie功能，无法登录！");
                    }
                }

                //var user = _userAppService.CheckUser(model.UserName, model.Password);
                //if (user != null)
                //{
                //记录Session
                //HttpContext.Session.SetString("CurrentUserId", user.Id.ToString());
                //HttpContext.Session.Set("CurrentUser", ByteConvertHelper.Object2Bytes(user));
                //跳转到系统首页
                //return RedirectToAction("Index", "Home");
                //}
                ViewBag.ErrorInfo = "用户名或密码错误。";
                //return View();
            }
            foreach (var item in ModelState.Values)
            {
                if (item.Errors.Count > 0)
                {
                    ViewBag.ErrorInfo = item.Errors[0].ErrorMessage;
                    break;
                }
            }

            return View(model);
        }

        public IActionResult Error()
        {
            return View();
        }
    }
}
